/* eslint-disable no-undef */
import React, { Component } from 'react';
import { Table, Tooltip } from 'antd';
import uuid from 'node-uuid';
import ShowTableCell from '../ShowTableCell';
import styles from './MergeTable.css';
import * as config from '../../../utils/config';
import * as commonFunc from '../commonFunc';

class MergeTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      app: props.app,
      componentName: props.componentName,
      columns: [], /* 合并后的表头 */
      data: [], /* 整合后的数据 */
      pages: { pageNum: 0, totalCount: 0 }, /* 页码 */
      dataUrl: `${config.server_host}business/getBusinessDataByFormcustomId/${props.config.sId}?sModelsId=${props.formId}`, /* 请求业务数据地址 */
      selectedRowKeys: [], /* 选择数据 */
      // selectedFieldKey: '',
      scrollX: 37,
      totalRow: false, /* 是否存在汇总行 */
      totalMap: {}, /* 数据汇总 */
      sFilterOrderBy: '',
      order: 'desc',
    };
    this.scrollY = 0;
  }

  componentWillMount() {
    const { gdsconfigformslave } = this.props.config;
    const mergeConfig = commonFunc.getConfigCondition(gdsconfigformslave, 'bVisible');
    const columns = [];
    let { scrollX } = this.state;
    let totalRow = false;
    const { totalMap } = this.state;
    mergeConfig.map((child, i) => {
      const childColumns = {
        title: child.showName,
        dataIndex: child.sName,
        key: child.sName,
        // sorter: true,
        width: child.iFitWidth === 0 ? 120 : child.iFitWidth,
        render: (text, record) => this.renderColumns(child.sName, text, record, child.iFitWidth),
        onCell: (record) => { return { onClick: () => this.onCellClick(record, child) }; },
        onHeaderCell: (column) => { return { onClick: () => this.handleHeaderCellClick(column) }; },
      };
      if (child.bSum) {
        totalRow = true;
        totalMap[`${child.sName}`] = '';
      }
      const iWidth = child.iFitWidth === 0 ? 120 : child.iFitWidth;
      scrollX += iWidth;
      const indexLine = child.showName.indexOf('-');
      const title = child.showName.substr(indexLine + 1);
      const childTitle = child.showName.substr(0, indexLine);
      /* 此处判断为之前存在表头大类便进行合并 */
      const flag = i > 0 ? columns.filter(item => item.title === childTitle).length > 0 ? 1 : -1 : -1;
      if (indexLine > -1) {
        if (columns.length === 0 || flag === -1) {
          const obj = {
            title: childTitle,
            children: [{ ...childColumns, title }],
          };
          columns.push(obj);
        } else if (flag > -1) {
          /* 此处判断为之前存在表头大类便进行合并 */
          columns.filter(item => item.title === childTitle)[0].children.push({ ...childColumns, title });
        }
      } else {
        columns.push(childColumns);
      }
      return true;
    });
    this.setState({
      columns, scrollX, totalRow, totalMap,
    });
    this.getData(config.pageNum, {}, {});
  }

  componentDidMount() {
    // this.handleWidth();
    // window.addEventListener('scroll', this.handleScroll.bind(this));
  }

  componentWillReceiveProps(nextProps) {
    // this.handleWidth();
    // const { dispatch } = nextProps;
    const { filterCondition } = nextProps;
    const { dataList } = nextProps.content;
    const {
      sDataListTabId, componentName, pages, loading, returnType, dataTotal,
    } = dataList;
    const urlData = nextProps.masterData;
    if (nextProps.sTabId === sDataListTabId && this.state.componentName === componentName) {
      if (loading) {
        return;
      } else if (returnType === 'isGetData') {
        this.getData(config.pageNum, {}, {}, filterCondition);
        return;
      }
      /* 暂时隐藏 */
      // else if (returnType === 'isGetFormInfo') {
      //   /* 前台无，可能来自后台 */
      //   const { selectedFieldKey } = this.state;
      //   const paneKey = new Date().getTime().toString(); /* Tab标签Id */
      //   const formId = urlData.sId; /* 窗体Id */
      //   const route = `${urlData.sName}/${selectedFieldKey}`;
      //   const paramInfo = { dataId: selectedFieldKey, srcTabId: this.props.sTabId, srcComponentName: this.state.componentName };
      //   const pane = {
      //     title: urlData.sMenuName, route, formId, key: paneKey, paramInfo,
      //   };
      //   dispatch({ type: 'app/addPane', payload: { pane } });
      //   return;
      // }
      /* 计算表格适配高度 */
      if (this.scrollY === 0) {
        const { currentPane, panes } = this.state.app;
        const indexPanel = panes.findIndex(item => item.key === currentPane.key);
        const tabContent = document.getElementsByClassName('ant-tabs-content')[0];
        const tabpanel = tabContent.children[indexPanel];
        const header = tabpanel.getElementsByTagName('table')[0];
        const headerHeight = header.offsetHeight;
        const fastFilter = tabpanel.getElementsByClassName('ant-layout-content')[0];
        const fastFilterHeight = fastFilter.offsetHeight;
        this.scrollY = `calc(100vh - ${headerHeight}px - ${fastFilterHeight}px - 179px)`;
      }
      let index = 1;
      /* 使用sSlaveId作为唯一键值对,考虑到列表可能以从表数据为主,会存在多条主表ID一致数据,列表在配置时需配置sSlaveId */
      for (const value of urlData) {
        value.key = `${value.sSlaveId}-${index}`;
        index += 1;
      }
      const data = [];
      urlData.forEach((child) => {
        const keyUuid = `${Date.now()}${uuid.v4()}`;
        const key = `${keyUuid}-${child.key.split('-')[1]}`;
        child.key = key;
        data.push(child);
      });
      /* 对列表数据进行处理,列表或者未清会使用复制到功能,弹窗数据格式为key[-]vale,所以在展示时需要对数据继续处理 */
      for (const v of data) {
        for (const mapV of Object.keys(v)) {
          if (v[`${mapV}`] !== null && v[`${mapV}`].toString().indexOf('[-]') > -1) {
            v[`${mapV}`] = v[`${mapV}`].substr(v[`${mapV}`].indexOf('[-]') + 3);
          }
        }
      }
      const { totalMap, totalRow } = this.state;
      if (totalRow) {
        if (dataTotal !== undefined && dataTotal.length > 0) {
          data.push({ key: `-${new Date().getTime()}`, dataTotal: true, ...dataTotal[0] });
          this.setState({ totalMap: { ...this.state.totalMap, ...dataTotal[0] } });
        } else {
          data.push({ key: `-${new Date().getTime()}`, dataTotal: true, ...totalMap });
        }
      }
      this.setState({ data, pages });
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { dataList } = nextProps.content;
    const { sDataListTabId, componentName } = dataList;
    if (nextState.selectedRowKeys !== this.state.selectedRowKeys) return true;
    return nextProps.sTabId === sDataListTabId && nextState.componentName === componentName;
  }

  // componentWillUnmount() {
  //   window.removeEventListener('scroll', this.handleScroll.bind(this));
  // }

  onCellClick = (record, info) => {
    const newsId = record.sId; /* 表格行的sId */
    if (info.sName === 'picArr') {
      const tableConfig = this.props.config;
      /* table中获取弹出框的sName作为route */
      const { sActiveId } = info; /* 窗体Id */
      const sNameUrl = `${config.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`;
      const value = {
        disabled: true,
        newsId,
        sActiveId,
        sNameUrl,
        sParentId: tableConfig.sParentId,
        componentName: tableConfig.sTbName,
      };
      this.props.onRouteName(value);
    }
  };

  onSelectChange = (selectedRowKeys) => {
    /* 隐藏过滤汇总项放在外部删除时过滤，在内部过滤会影响表格的正常全选反选功能 --2018-04-10 fjq */
    /* 过滤汇总项 */
    /* for (const child of selectedRows) {
      if (child.dataTotal !== undefined) {
        selectedRowKeys.splice(selectedRowKeys.findIndex(item => item === child.key), 1);
      }
    } */
    /* 选择数据 */
    this.setState({ selectedRowKeys });
    this.props.onSelectedRowKeys(selectedRowKeys);
  };

  getData(pageNum, filters, column, filterCondition) {
    const { dataUrl, componentName } = this.state;
    const { sTabId, dispatch } = this.props;
    const sort = this.state.order === 'desc' ? 'asc' : 'desc';
    const sFilterOrderBy = Object.keys(column).length > 0 && column.key ? { [column.key]: sort } : ''; // 后端未支持空对象， 先用空表示
    let ret = true;
    if (column && column.columnKey && column.columnKey === 'selection-column') {
      ret = false;
    }
    if (ret) {
      const value = {
        bFilter: filterCondition !== undefined && filterCondition.length > 0 ? filterCondition : this.props.filterCondition,
        pageNum,
        pageSize: config.pageSize,
        sFilterOrderBy,
      };
      if (this.props.onValue) {
        this.props.onValue(value);
      }
      this.setState({ sFilterOrderBy, order: sort });
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: dataUrl, sTabId, componentName, value,
        },
      });
    }
  }

  handleHeaderCellClick = (column) => {
    const { pages } = this.state;
    this.getData(pages.pageNum, {}, column);
  };

  handleTableChange = (pagination, filters, column) => {
    /* 表分页，排序，筛选时的变化，后台抓取数据 */
    this.getData(pagination.current, filters, column);
  };

  handleDoubleClick = (record) => {
    const newsId = record.sId; /* 表格行的sId */
    const newKey = record.key;
    const tableConfig = this.props.config;
    /* table中获取弹出框的sName作为route */
    const { gdsconfigformslave } = tableConfig;
    const { sFilterOrderBy, pages, data } = this.state;
    const obj = gdsconfigformslave.filter(item => (item.sName === 'picArr'));
    if (obj.length > 0) {
      let sActiveId = '';
      if (obj[0].sName === 'picArr' && obj[0].sDropDownType === 'picArr') {
        [{ sActiveId }] = obj;
      }
      const sNameUrl = `${config.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`;
      const value = {
        disabled: true,
        newsId,
        sActiveId,
        sNameUrl,
        sParentId: tableConfig.sParentId,
        componentName: tableConfig.sTbName,
        sFilterOrderBy,
        pageSize: config.pageSize,
        pages,
        currentData: data,
        bFilter: this.props.filterCondition,
        newKey,
        refresh: this.props.onRefresh,
        currentIndex: data.findIndex(item => item.sId === record.sId),
      };
      this.props.onRouteName(value);
    }
  };

  // handleWidth = () => {
  //   const tableHead = document.getElementById('mergeTable').getElementsByClassName('ant-table-header')[0];
  //   const tableBody = document.getElementById('mergeTable').getElementsByClassName('ant-table-body')[0];
  //   // 设置宽度一致
  //   tableHead.style.width = `${tableBody.offsetWidth}px`;
  //   // 设置滚动一致
  //   tableBody.onScroll = function () {
  //     tableHead.scrollLeft = tableBody.scrollLeft;
  //   };
  // };

  // handleScroll = () => {
  //   const root = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
  //   const mergeTable = document.getElementById('mergeTable');
  //   if (root > 105) {
  //     mergeTable.className = 'mergeTable';
  //   } else {
  //     mergeTable.className = '';
  //   }
  // };

  renderColumns = (dataIndex, text, record, width) => {
    const sWidth = width === 0 ? 120 : width;
    if (record.dataTotal !== undefined) {
      return (
        <div className={styles.editSpan}>
          <Tooltip title={text} mouseLeaveDelay={0} placement="topLeft">
            <span style={{ width: width - 5 }}>{text}</span>
          </Tooltip>
        </div>
      );
    } else {
      return (<ShowTableCell
        dataIndex={dataIndex}
        value={text}
        width={sWidth}
      />);
    }
  };

  render() {
    const {
      columns, data, pages, selectedRowKeys, scrollX, totalRow,
    } = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        style: record.dataTotal === true ? { display: 'none' } : {},
      }),
    };
    const { totalCount } = pages;
    const quality = Math.ceil(`${totalCount / config.pageSize}`);
    return (
      <div id="mergeTable">
        <Table
          size="middle"
          columns={columns}
          dataSource={data}
          rowSelection={rowSelection}
          bordered
          pagination={{
            size: 'large',
            defaultPageSize: config.pageSize,
            pageSize: totalRow ? config.pageSize + 1 : config.pageSize,
            total: totalRow ? pages.totalCount + quality : pages.totalCount,
            showQuickJumper: true,
            current: pages.pageNum,
            className: `${styles.pagination}`,
          }}
          onChange={this.handleTableChange}
          onRow={(record) => { return { onDoubleClick: () => { this.handleDoubleClick(record); } }; }}
          scroll={{ x: scrollX, y: this.scrollY }}
          onScroll={this.handleScroll}
        />
      </div>
    );
  }
}

export default MergeTable;
